const express = require("express");
const router = express.Router();

// 使用multer上传文件并重命名为10为数字和大小写字母 把文件存到public/uploads文件夹下并返回路径
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../../public/uploads');
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname);
        const randomName = Array(10)
            .fill(null)
            .map(() => Math.random().toString(36).charAt(2))
            .join('');
        cb(null, randomName + ext);
    }
});

const upload = multer({ storage: storage });

router.post('/', upload.single('file'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ error: 'No file uploaded' });
    }
    const filePath = `svg/${req.file.filename}`;
    res.json({ path: filePath });
});

module.exports = router;
